// @ts-nocheck
const express = require('express');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const router = express.Router();
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });
const axios = require('axios');
const { errorMsg, successMsg } = require('../public/constant');


const uploadsDir = path.resolve(__dirname, '../assets/uploads/');
const storage = multer.diskStorage({
    destination: uploadsDir,
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
const upload1 = multer({
    storage: storage,
}).single('file');
// 上传图片
router.post('/Img', upload.single('file'), (req, res, next) => {
    if (!req.file) {
        res.status(400).send(errorMsg('上传文件不能为空'))
    }
    const formData = new FormData();
    formData.append('file', req.file.buffer, {
        filename: req.file.originalname,
        contentType: req.file.mimetype,
    });
    formData.append('token', '45281f8430884952b675cabb4ba71951')
    const uploadConfig = {
        method: 'post',
        url: 'https://api.superbed.cn/upload',
        headers: {
            ...formData.getHeaders()
        },
        data: formData
    };
    axios(uploadConfig).then(resu => {
        if (resu.data.err == 0) {
            res.status(200).send(successMsg(resu.data.url))
        } else {
            res.status(400).send(errorMsg())
        }
    }).catch(err => {
        res.status(500).send(errorMsg(err))
    })

});
router.post('/UploadImg', (req, res) => {
    upload1(req, res, (err) => {
        if (err) {
            res.status(500).send(errorMsg(err))
        } else {
            res.status(200).send(successMsg(`/uploads/${req.file.filename}`))
        }
    });
});

module.exports = router;